package com.partners.handler;

import com.partners.dao.bo.FansDO;
import com.partners.service.FansService;
import com.partners.utils.SessionManager;
import com.partners.utils.TimestampUtils;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {

    @Resource
    private FansService fansService;


    @Resource
    private SessionManager sessionManager;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager wxsessionManager) {
        String openId = wxMessage.getFromUser();
        //this.logger.info("取消关注用户 OPENID: " + openId);
        // TODO 可以更新本地数据库为取消关注状态
        Integer fanId = fansService.getFansByOpenId(openId);
        this.logger.info("取消用户信息{}",wxMpService.getUserService());
        if(fanId != null){
            //更新粉丝为取消关注状态
            Integer unfollowTime = TimestampUtils.timestamp();
            Byte follow = 0;
            FansDO fansDO = new FansDO();
            fansDO.setFanid(fanId);
            fansDO.setUnfollowtime(unfollowTime);
            fansDO.setFollow(follow);
            fansService.UpdateFans(fansDO);
            //清楚缓存
            sessionManager.delete(openId);
        }
        return null;
    }

}
